<?php

namespace common\jobs\handle;

use Yii;
use common\models\trade\Trade;

/**
 * 订单通知队列操作
 *
 * @package common\jobs\handle
 * @property Trade|null $model
 */
class BusinessNotifyHandle extends \common\jobs\base\BaseJobHandleModel {

    /**
     * @var integer 交易ID
     */
    public $trade_id = null;

    /**
     * @var Trade|null 交易
     */
    private $_model = null;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['trade_id'], 'required'],
            [['trade_id'], 'integer'],
            [['trade_id'], 'validateTrade'],
        ];
    }

    /**
     * 校验订单信息
     *
     * @param string $attribute the attribute currently being validated
     */
    public function validateTrade($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $trade = Trade::findOne($this->$attribute);
        if (!$trade) {
            return $this->addError($attribute, '【' . $this->$attribute . '】交易不存在！');
        }
        if (!$trade->validatePaymentStatus()) {
            return $this->addError($attribute, '【' . $this->$attribute . '】交易未支付！');
        }
        $this->_model = $trade;
    }

    /**
     * 获取交易信息
     *
     * @return Trade|null
     */
    public function getModel() {
        return $this->_model;
    }

    /**
     * 执行业务通知
     * @return boolean
     * @throws \common\jobs\base\IntervalRetryJobException
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('业务通知失败');
        }
        //获取订单信息
        $trade = $this->getModel();
        $status = $trade->notify();
        if (!$status) {
            $this->dumpRetryError('业务通知失败，等待重试');
        }
        return true;
    }

}
